<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------
namespace Admin\Model;
use Think\Model;
/**
 * 分类模型
 * @author jry <598821125@qq.com>
 */
class UserModel extends Model{
    /**
     * 自动验证规则
     * @author jry <598821125@qq.com>
     */
    protected $_validate = array(
        //验证用户名
        array('username', 'require', '用户名不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        array('username', '1,16', '用户名长度为1-16个字符', self::EXISTS_VALIDATE, 'length', self::MODEL_BOTH),
        array('username', '', '用户名已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),
        array('username', 'checkIP', '注册太频繁请稍后再试', self::EXISTS_VALIDATE, 'callback', self::MODEL_INSERT), //IP限制
        array('username', '/^(?!_)(?!\d)(?!.*?_$)[\w\一-\龥]+$/', '用户名只可含有汉字、数字、字母、下划线且不以下划线开头结尾，不以数字开头！', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),

        //验证密码
        array('password', '6,30', '密码长度为6-30位', self::EXISTS_VALIDATE, 'length', self::MODEL_BOTH),
        array('password', '/(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*()_+{}:"<>?\-=[\];\',.\/]+)$)^[\w~!@#$%^&*()_+{}:"<>?\-=[\];\',.\/]+$/', '密码至少由数字、字符、特殊字符三种中的两种组成', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),

        //验证邮箱
        array('email', 'email', '邮箱格式不正确', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        array('email', '1,32', '邮箱长度为1-32个字符', self::EXISTS_VALIDATE, 'length', self::MODEL_BOTH),
        array('email', '', '邮箱被占用', self::EXISTS_VALIDATE, 'unique', self::MODEL_BOTH),

        //验证手机号码
        array('mobile', '/^1\d{10}$/', '手机号码格式不正确', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        array('mobile', '', '手机号被占用', self::EXISTS_VALIDATE, 'unique', self::MODEL_BOTH),
    );

    /**
     * 自动完成规则
     * @author jry <598821125@qq.com>
     */
    protected $_auto = array(
        array('password', 'user_md5', self::MODEL_BOTH, 'function'),
        array('reg_time', NOW_TIME, self::MODEL_INSERT),
        array('reg_ip', 'get_client_ip', self::MODEL_INSERT, 'function', 1),
        array('ctime', NOW_TIME, self::MODEL_INSERT),
        array('utime', NOW_TIME, self::MODEL_BOTH),
        array('sort', '0', self::MODEL_INSERT),
        array('status', '1', self::MODEL_INSERT),
    );

    /**
     * 根据ID获取用户
     * @author jry <598821125@qq.com>
     */
    public function getUserById($id){
        $map['id'] = array('eq', $id);
        return $this->where($map)->find();
    }

    /**
     * 获取所有用户
     * @author jry <598821125@qq.com>
     */
    public function getAllUser($map, $status = '0,1'){
        $map['status'] = array('in', $status);
        return $this->where($map)->order('id asc')->select();
    }

    /**
     * 获取所有所有用户指定字段值
     * @param string $field 字段
     * @return array
     * @author jry <598821125@qq.com>
     */
    public function getColumnByfield($field = 'email', $map){
        $map['status'] = array('eq', 1);
        return $this->where($map)->getField($field,true);
    }

    /**
     * 用户登录
     * @author jry <598821125@qq.com>
     */
    public function login($username, $password, $map){
        if(preg_match("/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/", $username)){
            $map['email'] = array('eq', $username); //邮箱登陆
        }elseif(preg_match("/1\d{10}$/", $username)){
            $map['mobile'] = array('eq', $username); //手机号登陆
        }else{
            $map['username'] = array('eq', $username); //用户名登陆
        }
        $map['password'] = array('eq', user_md5($password));
        $map['status']   = array('eq', 1);
        $user = $this->where($map)->find(); //查找用户
        if($user){
            /* 更新登录信息 */
            $data = array(
                'uid'             => $user['id'],
                'login'           => array('exp', '`login`+1'),
                'last_login_time' => NOW_TIME,
                'last_login_ip'   => get_client_ip(1),
            );
            $this->save($data);
            /* 记录登录SESSION和COOKIES */
            $auth = array(
                'uid'             => $user['id'],
                'username'        => $user['username'],
                'last_login_time' => $user['last_login_time'],
                'last_login_ip'   => get_client_ip(1),
            );
            session('user_auth', $auth);
            session('user_auth_sign', data_auth_sign($auth));
        }
        return $user['id'];
    }

    /**
     * 检测同一IP注册是否频繁
     * @return boolean ture 正常，false 频繁注册
     * @author jry <598821125@qq.com>
     */
    protected function checkIP(){
        $limit_time = C('LIMIT_TIME_BY_IP');
        $map['reg_time'] = array('GT', time()-(int)$limit_time);
        $reg_ip = $this->getColumnByfield('reg_ip', $map);
        $key = array_search(get_client_ip(1), $reg_ip);
        if($reg_ip && $key !== false){
            return false;
        }
        return true;
    }
}
